from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField, IntegerField, DateTimeField
from wtforms.validators import DataRequired, Email, EqualTo, ValidationError, Length
from models import User, Course
from flask import url_for, redirect

class LoginForm(FlaskForm):
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    password = PasswordField('密码', validators=[DataRequired()])
    remember_me = BooleanField('记住我')
    submit = SubmitField('登录')

    def validate_email(self, field):
        # 验证逻辑
        return True  # 或者抛出 ValidationError

class RegisterForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired()])
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    phone = StringField('手机号', validators=[DataRequired(), Length(min=11, max=11)])
    password = PasswordField('密码', validators=[DataRequired()])
    password2 = PasswordField('确认密码', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('注册')
    
    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('该用户名已被使用')
            
    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('该邮箱已被注册')

class BookingForm(FlaskForm):
    course = SelectField('选择课程', coerce=int, validators=[DataRequired()])
    coach = SelectField('选择教练', coerce=int, validators=[DataRequired()])
    date = DateTimeField('预约日期时间', format='%Y-%m-%d %H:%M', validators=[DataRequired()])
    participants = IntegerField('参与人数', default=1, validators=[DataRequired()])
    is_group = BooleanField('是否拼团')
    submit = SubmitField('预约')
    
    def __init__(self, *args, **kwargs):
        super(BookingForm, self).__init__(*args, **kwargs)
        # 在初始化时设置课程选项
        self.course.choices = [(c.id, f"{c.name} - ¥{c.price}") for c in Course.query.all()]

class ContactForm(FlaskForm):
    name = StringField('姓名', validators=[DataRequired()])
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    phone = StringField('手机号', validators=[DataRequired()])
    message = TextAreaField('留言', validators=[DataRequired()])
    submit = SubmitField('提交') 